from django.contrib.auth.backends import ModelBackend

from users.models import User


class UsernameMobileLogin(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """

        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return: User对象
        """
        try:
            user = User.objects.get(username=username)

        except Exception as e:
            user = None

        if not user:
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                return None

        # 密码没有检查通过
        if not user.check_password(password):
            return None

        return user